package com.lwj.mallchat.common.user.service.impl;

import com.lwj.mallchat.common.common.constant.RedisKey;
import com.lwj.mallchat.common.common.utils.JwtUtils;
import com.lwj.mallchat.common.common.utils.RedisUtils;
import com.lwj.mallchat.common.user.service.LoginService;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author lwj
 * @ClassName LoginServiceImpl
 * @date 2024/10/17 21:00
 */
@Service
public class LoginServiceImpl implements LoginService {

    public static final int TOKEN_EXPIRE_DAY = 3;
    public static final int TOKEN_RENEW_DAY = 1;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public void renewalTokenIfNecessary(String token) {
        Long uid = getValidUid(token);
        String userTokenKey = getUserTokenKey(uid);
        Long expireDay = RedisUtils.getExpire(userTokenKey, TimeUnit.DAYS);
        if(expireDay==-2){
            //不存在的key
            return;
        }
        if (expireDay< TOKEN_RENEW_DAY){
            RedisUtils.expire(getUserTokenKey(uid), TOKEN_EXPIRE_DAY, TimeUnit.DAYS);
        }

    }

    @Override
    public String login(Long id) {
        String token = jwtUtils.createToken(id);
        RedisUtils.set(getUserTokenKey(id), token, TOKEN_EXPIRE_DAY, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Long getValidUid(String token) {
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) {
            return null;
        }

        String oldToken = RedisUtils.getStr(getUserTokenKey(uid));
        if (StringUtil.isBlank(oldToken)) {
            return null;
        }
        return Objects.equals(token, oldToken) ? uid : null;
    }

    private String getUserTokenKey(Long uid) {
        return RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
    }
}
